/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelCadastroCliente.java
 *
 * Created on 29/09/2011, 18:11:04
 */

package modules.enderecamento.gui.jpanel;

import java.util.List;
import java.util.Map;
import javax.swing.JFormattedTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import modules.enderecamento.facade.WMSFacade;
import modules.enderecamento.models.dto.Cliente;
import modules.enderecamento.models.dto.Permissao;
import modules.enderecamento.security.WMSSession;
import modules.enderecamento.util.BoxPanel;
import modules.enderecamento.util.Funcoes;

/**
 *
 * @author Clezio
 */
public class PanelCadastroCliente extends javax.swing.JPanel {

    private WMSFacade wmsFacade;
    private MaskFormatter formatoCnpj;
    private boolean permissaoAdicionarGlobal;
    /** Creates new form PanelCadastroCliente */
    public PanelCadastroCliente() {
        try {
            formatoCnpj = new MaskFormatter("##.###.###.####-##");
        } catch (Exception erro) {
            Funcoes.registrarLog(erro);
        }
        initComponents();
        wmsFacade = new WMSFacade();
        checaPermissao();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfId = new modules.enderecamento.gui.custom.WMSJTextField();
        lbId = new modules.enderecamento.gui.custom.WMSLabel();
        lbNome = new modules.enderecamento.gui.custom.WMSLabel();
        tfNome = new modules.enderecamento.gui.custom.WMSJTextField();
        lbCnpj = new modules.enderecamento.gui.custom.WMSLabel();
        tfCnpj = new JFormattedTextField(formatoCnpj);
        btnSalvar = new modules.enderecamento.gui.custom.WMSJButton();
        btnNovo = new modules.enderecamento.gui.custom.WMSJButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.enderecamento.gui.custom.WMSJTable();
        btnExcluir = new modules.enderecamento.gui.custom.WMSJButton();
        btnAlterar = new modules.enderecamento.gui.custom.WMSJButton();
        lbRazaoSocial = new modules.enderecamento.gui.custom.WMSLabel();
        tfRazaoSocial = new modules.enderecamento.gui.custom.WMSJTextField();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cadastro de Clientes");

        tfId.setEditable(false);
        tfId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfIdKeyPressed(evt);
            }
        });

        lbId.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbId.setText("ID:");

        lbNome.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbNome.setText("Nome:");

        tfNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfNomeKeyPressed(evt);
            }
        });

        lbCnpj.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbCnpj.setText("Cnpj:");

        tfCnpj.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfCnpjFocusLost(evt);
            }
        });
        tfCnpj.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfCnpjKeyPressed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnNovo.setText("Novo");
        btnNovo.setEnabled(false);
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Nome", "Razão Social", "Cnpj", "Ativo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        lbRazaoSocial.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbRazaoSocial.setText("Razão Social:");

        tfRazaoSocial.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfRazaoSocialKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 800, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lbId, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lbRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tfRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lbCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tfCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(155, 155, 155)
                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 780, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(310, 310, 310)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17)
                .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 54, 54)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbId, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(lbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(lbRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(tfRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(lbCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(tfCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfIdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfIdKeyPressed
        if(evt.getKeyCode() == evt.VK_ENTER){
            save();
        }
}//GEN-LAST:event_tfIdKeyPressed

    private void tfNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfNomeKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfRazaoSocial.requestFocus();
        }else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfNome.setText("");
            tfNome.requestFocus();
        }
}//GEN-LAST:event_tfNomeKeyPressed

    private void tfCnpjFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfCnpjFocusLost

}//GEN-LAST:event_tfCnpjFocusLost

    private void tfCnpjKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfCnpjKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            save();
        }else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfRazaoSocial.requestFocus();
            tfCnpj.setText("");
        }
}//GEN-LAST:event_tfCnpjKeyPressed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        save();
}//GEN-LAST:event_btnSalvarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        clearFields();
        btnNovo.setEnabled(false);
}//GEN-LAST:event_btnNovoActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        excluir();
}//GEN-LAST:event_btnExcluirActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int selected = jTable1.getSelectedRow();
            int id = (Integer) modelo.getValueAt(selected, 0);
            Cliente cliente = wmsFacade.obterClienteById(id);
            if (cliente != null) {
                tfId.setText("" + cliente.getId());
                tfNome.setText(cliente.getNome());
                tfRazaoSocial.setText(cliente.getRazaoSocial());
                tfCnpj.setText(cliente.getCnpj());
                btnNovo.setEnabled(true);
            }
        }else{
            BoxPanel.showMessageDialog(null, "Selecione um Cliente");
        }
}//GEN-LAST:event_btnAlterarActionPerformed

    private void tfRazaoSocialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRazaoSocialKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfCnpj.requestFocus();
        }else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfNome.requestFocus();
            tfRazaoSocial.setText("");
        }
    }//GEN-LAST:event_tfRazaoSocialKeyPressed

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        clearFields();
        listarClientes(wmsFacade.listarClientes("from Cliente order by nome"));
    }//GEN-LAST:event_formAncestorAdded


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.enderecamento.gui.custom.WMSJButton btnAlterar;
    private modules.enderecamento.gui.custom.WMSJButton btnExcluir;
    private modules.enderecamento.gui.custom.WMSJButton btnNovo;
    private modules.enderecamento.gui.custom.WMSJButton btnSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private modules.enderecamento.gui.custom.WMSJTable jTable1;
    private modules.enderecamento.gui.custom.WMSLabel lbCnpj;
    private modules.enderecamento.gui.custom.WMSLabel lbId;
    private modules.enderecamento.gui.custom.WMSLabel lbNome;
    private modules.enderecamento.gui.custom.WMSLabel lbRazaoSocial;
    private javax.swing.JTextField tfCnpj;
    private modules.enderecamento.gui.custom.WMSJTextField tfId;
    private modules.enderecamento.gui.custom.WMSJTextField tfNome;
    private modules.enderecamento.gui.custom.WMSJTextField tfRazaoSocial;
    // End of variables declaration//GEN-END:variables

    private void checaPermissao(){
        permissaoAdicionarGlobal = true;
        Map<Integer,Permissao> mapPermissoes = WMSSession.getInstance().getMapPermissoes();
        boolean permissaoAlterar = mapPermissoes.containsKey(3);
        boolean permissaoExcluir = mapPermissoes.containsKey(4);
        boolean permissaoAdicionar = mapPermissoes.containsKey(2);

        if(!permissaoAlterar){btnAlterar.setVisible(false);}
        if(!permissaoExcluir){btnExcluir.setVisible(false);}
        if(!permissaoAdicionar && !permissaoAlterar){
            ocultarCamposFormulario();
        }else if(!permissaoAdicionar){
            btnNovo.setVisible(false);
            permissaoAdicionarGlobal = false;
        }
    }

    private void ocultarCamposFormulario() {
        //oculta do formulário
        lbId.setVisible(false);
        lbNome.setVisible(false);
        lbRazaoSocial.setVisible(false);
        lbCnpj.setVisible(false);
        tfId.setVisible(false);
        tfNome.setVisible(false);
        tfRazaoSocial.setVisible(false);
        tfCnpj.setVisible(false);
        btnSalvar.setVisible(false);
        btnNovo.setVisible(false);
    }
    
    private void clearFields() {
        tfId.setText("");
        tfNome.setText("");
        tfRazaoSocial.setText("");
        tfCnpj.setText("");
        tfNome.requestFocus();
    }

    private void listarClientes(List<Cliente> clientes) {
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(50);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(50);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(45);

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        for (int i = 0; i < clientes.size(); i++) {
            int id = clientes.get(i).getId();
            String nome = clientes.get(i).getNome();
            String razaoSocial = clientes.get(i).getRazaoSocial();
            String cnpj = clientes.get(i).getCnpj();
            String ativo = "Não";
            if (clientes.get(i).isAtivo()) {
                ativo = "Sim";
            }
            modelo.addRow(new Object[]{
                        id, nome,razaoSocial, cnpj, ativo
                    });
        }
    }

    private void save() {
        //Checa permissao
        if (tfId.getText().length() == 0 && !permissaoAdicionarGlobal) {
            BoxPanel.showMessageDialog(null, "Usuário sem permissão para adicionar novo registro.");
            return;
        }

        Cliente obj = new Cliente();
        obj.setNome(tfNome.getText().toUpperCase());
        obj.setRazaoSocial(tfRazaoSocial.getText().toUpperCase());
        obj.setCnpj(tfCnpj.getText());
        obj.setAtivo(true);
        if (tfId.getText().length() > 0) {
            obj.setId(Integer.parseInt(tfId.getText()));
        }

        if (wmsFacade.saveCliente(obj)) {
            clearFields();
            listarClientes(wmsFacade.obterClientes("from Cliente order by nome"));
            btnNovo.setEnabled(false);
            BoxPanel.showMessageDialog(null, "Cliente salvo com sucesso.");
        }
    }

    private void excluir() {
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int[] selected = jTable1.getSelectedRows();
            for (int i = 0; i < selected.length; i++) {
                int id = (Integer) modelo.getValueAt(selected[i], 0);
                wmsFacade.deleteCliente(wmsFacade.obterClienteById(id));
                modelo.removeRow(jTable1.getSelectedRow());
            }
            listarClientes(wmsFacade.listarClientes("from Cliente order by nome"));
        } else {
            BoxPanel.showMessageDialog(null, "Selecione um Cliente");
        }
    }

}
